package cn.jianml.excel.controller;

import cn.jianml.excel.Listener.ImportExcelListener;
import cn.jianml.excel.Listener.UserExcelListener;
import cn.jianml.excel.entity.User;
import cn.jianml.excel.service.UserService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author wujian
 * @time 2020/1/6
 */
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 导入Excel数据(默认异步读取excel)
     */
    @PostMapping("/import")
    public String importExcels(@RequestParam("file") MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), User.class, new ImportExcelListener(userService)).sheet().doRead();
        return "导入成功";
    }

    /**
     * 导出 Excel
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response) throws IOException{
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("测试", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), User.class).sheet("模板").doWrite(userService.getData());
    }

    /**
     * 导入Excel数据(优化后)
     */
    @PostMapping("/commonImport")
    public String commonImportExcels(@RequestParam("file") MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), User.class, new UserExcelListener(userService)).sheet().doRead();
        return "导入成功";
    }


}
